<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactStage\Contract\ContactStageRuleContract;

/**
 * 阶段旅程添加.
 *
 * Class Index.
 * @Controller
 */
class RuleStore extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ContactStageRuleContract
     */
    protected $contactStageRuleService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @RequestMapping(path="/dashboard/contactStage/ruleStore", methods="POST")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 接收参数
        $params = [
            'route_name' => $this->request->input('routeName'),
            'stage_auto' => (int) $this->request->input('stageAuto', 0),
            'remind_auto' => (int) $this->request->input('remindAuto', 0),
            'type' => (int) $this->request->input('type', 0),
        ];
        $this->validated($params);
        $user = user();

        $data = $this->contactStageRuleService->getContactStageRuleByCorpId($user['corpIds'][0], ['id']);

        // 数据操作
        Db::beginTransaction();
        try {
            if ($data) {
                $params['type'] === 1 && $this->contactStageRuleService->updateContactStageRuleById($data['id'], ['route_name' => $params['route_name']]);
                $params['type'] === 2 && $this->contactStageRuleService->updateContactStageRuleById($data['id'], ['stage_auto' => $params['stage_auto']]);
                $params['type'] === 3 && $this->contactStageRuleService->updateContactStageRuleById($data['id'], ['remind_auto' => $params['remind_auto']]);
            } else {
                // 入库
                $params['corp_id'] = user()['corpIds'][0];
                empty($params['route_name']) && $params['route_name'] = '客户阶段';
                $res = $this->contactStageRuleService->createContactStageRule($params);
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '设置失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.required' => '类型 必传',
        ];
    }
}
